Popular Searches
Popular Course Categories
Popular Courses

Working with Intents and Intent Filters

Working with Intents and Intent Filters

Android Application Components and Lifecycle

Working with Intents and Intent Filters in Android

Course: Android App Development

Topic: Working with Intents and Intent Filters

Course Link: Android App Development Training - JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Intents in Android

An Intent is a messaging object used by Android applications to request an action from another application component. It allows activities, services, and broadcast receivers to communicate with each other and exchange information.

For example, when a user clicks a button to open a profile screen, share a message, open a website, or view a location on a map, an intent can be used to request the corresponding action.

Intents are an essential part of Android development because applications are built using independent components that often need to interact with one another.

Why Are Intents Important?

  • They allow navigation between activities.
  • They transfer data between application components.
  • They allow an app to request actions from other apps.
  • They support sharing text, images, links, and other content.
  • They help applications respond to specific system events.
  • They enable Android to identify suitable components for requested actions.

2. What Is an Intent?

An intent describes an operation that should be performed. Depending on its configuration, Android can send the intent directly to a named component or search for a component capable of handling the requested action.

An intent can contain information such as the destination component, action, data URI, MIME type, category, additional data, and launch flags.

Basic Intent Syntax in Kotlin

val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)

In this example:

  • Intent(this, SecondActivity::class.java) creates an explicit intent.
  • this refers to the current Activity context.
  • SecondActivity::class.java identifies the destination activity.
  • startActivity(intent) requests Android to launch the destination activity.

3. Types of Intents

Android primarily uses two types of intents: explicit intents and implicit intents.

3.1 Explicit Intent

An explicit intent identifies the exact component that should handle the request. It is commonly used for navigation between activities within the same application.

Example: Opening a product details screen from a product listing screen.

val intent = Intent(this, ProductDetailsActivity::class.java)
startActivity(intent)

Android does not need to search for a matching intent filter to determine the target of an explicit intent. The specified component is the destination, subject to Android's component access and security rules.

3.2 Implicit Intent

An implicit intent describes an action without specifying an exact destination component. Android searches for components that can handle the action and its associated data.

Example: Opening a website in a browser.

val intent = Intent(
    Intent.ACTION_VIEW,
    Uri.parse("https://www.justacademy.co/")
)

if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
}

Android can launch a suitable browser or another compatible application. If multiple applications can handle the request, Android may allow the user to select one.

Explicit vs. Implicit Intents

Feature Explicit Intent Implicit Intent
Destination Specified component Not specified directly
Resolution Targets a named component Android searches for a compatible component
Common use Internal screen navigation Opening websites and sharing content
Intent filter required Not required to identify the target Usually required for a component to advertise support
Example Opening ProfileActivity Requesting an app to display a website

4. Important Components of an Intent

4.1 Component Name

The component name identifies the activity, service, or other component that should receive an explicit intent.

val intent = Intent(this, SettingsActivity::class.java)

4.2 Action

The action describes what should happen. Android provides standard action constants for common operations.

Action Purpose
Intent.ACTION_VIEW Display content such as a web page or location.
Intent.ACTION_SEND Share content with another application.
Intent.ACTION_DIAL Open the phone dialer with an optional phone number.
Intent.ACTION_SENDTO Send content to a specified type of destination, commonly an email or SMS app.
Intent.ACTION_MAIN Identify a main entry point for an activity.

4.3 Data

The data field contains a URI that identifies the content or resource on which the action should operate.

val intent = Intent(
    Intent.ACTION_VIEW,
    Uri.parse("https://www.justacademy.co/")
)

4.4 MIME Type

A MIME type identifies the format of data. It can help Android find an application that supports the required content.

Examples include:

  • text/plain - Plain text.
  • image/jpeg - JPEG image.
  • image/* - Any supported image MIME subtype.
  • application/pdf - PDF document.

4.5 Category

A category provides additional information about the kind of component that can handle an intent.

  • Intent.CATEGORY_DEFAULT - Allows an activity to match ordinary implicit activity launches when included in its filter.
  • Intent.CATEGORY_LAUNCHER - Identifies an activity that should appear in the application launcher when combined with the appropriate main action.
  • Intent.CATEGORY_BROWSABLE - Allows a component to be considered for browser-originated links when the other filter conditions match.

4.6 Extras

Extras are key-value pairs used to transfer additional information with an intent.

val intent = Intent(this, ProfileActivity::class.java)
intent.putExtra("USER_NAME", "Aarav")
intent.putExtra("USER_AGE", 24)
startActivity(intent)

Here, the user's name and age are passed to the destination activity.

4.7 Flags

Intent flags provide instructions about activity launching and task-stack behavior. They should be used only when their behavior is appropriate for the application's navigation design.

val intent = Intent(this, HomeActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)

FLAG_ACTIVITY_CLEAR_TOP can remove activities above an existing target activity in the same task, depending on launch mode and other flags.

5. What Is an Intent Filter?

An intent filter is a declaration in the Android manifest that describes the implicit intents a component is prepared to handle. It enables Android to discover activities and other eligible components that support particular actions, categories, and data types.

For example, an application can declare an intent filter to receive plain text shared by another application or to handle a supported website link.

An intent filter is not a replacement for component security. An exported component can potentially be started explicitly by another application even when the incoming intent does not match its filter. Validate incoming data and configure component access appropriately.

6. Structure of an Intent Filter

Intent filters are declared inside the relevant component in AndroidManifest.xml.

<activity
    android:name=".ShareActivity"
    android:exported="false">

    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>

</activity>

This example declares that the activity can handle matching implicit intents for sharing plain text. Since the activity is not exported, other applications cannot directly launch it as an exported component; choose the exported value according to the intended app-to-app interaction.

6.1 The Action Element

The <action> element declares an action supported by the component.

<action android:name="android.intent.action.VIEW" />

6.2 The Category Element

The <category> element specifies a supported category. Activities receiving ordinary implicit activity launches generally need the default category in the filter.

<category android:name="android.intent.category.DEFAULT" />

6.3 The Data Element

The <data> element describes acceptable data schemes, hosts, paths, and MIME types.

<data
    android:scheme="https"
    android:host="www.justacademy.co" />

When the data declaration includes a scheme and host, Android uses these values during intent resolution. A complete filter must be designed for the specific links the application intends to support.

7. How Intent Filters Work

When an implicit intent is sent, Android compares it against the intent filters declared by eligible components on the device.

  1. The application creates an intent with an action and any required data.
  2. The application requests the operation, for example by calling startActivity().
  3. Android evaluates eligible components and their intent filters.
  4. The action, data, and category requirements must match.
  5. If a suitable component is found, Android can launch it or present a choice to the user when appropriate.
  6. The receiving component reads and validates the incoming intent before acting on it.

An explicit intent names its target directly and does not rely on intent-filter matching to select that target.

8. Launching Another Activity Using an Explicit Intent

Suppose an application contains MainActivity and ProfileActivity. A button in the main screen opens the profile screen.

MainActivity.kt

package com.example.intentdemo

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val profileButton =
            findViewById<Button>(R.id.profileButton)

        profileButton.setOnClickListener {
            val intent = Intent(
                this,
                ProfileActivity::class.java
            )
            startActivity(intent)
        }
    }
}

ProfileActivity.kt

package com.example.intentdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class ProfileActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_profile)
    }
}

Ensure both activities are declared in the manifest. Activities belonging to the same application can generally remain non-exported unless external access is required.

<application ...>
    <activity
        android:name=".ProfileActivity"
        android:exported="false" />

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

9. Passing Data Between Activities

Intents allow one activity to send information to another. Use clear keys for extras so the receiving activity can retrieve the expected values.

Sending Data

val intent = Intent(this, DetailsActivity::class.java)
intent.putExtra("PRODUCT_NAME", "Laptop")
intent.putExtra("PRODUCT_PRICE", 55000)
startActivity(intent)

Receiving Data

class DetailsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)

        val productName =
            intent.getStringExtra("PRODUCT_NAME")

        val productPrice =
            intent.getIntExtra("PRODUCT_PRICE", 0)

        // Use the received values to update the screen.
    }
}

The default value in getIntExtra() is returned if the requested integer extra is absent. Validate incoming values, especially when the activity can be launched by other applications.

10. Opening a Website Using an Implicit Intent

To open a web page, use Intent.ACTION_VIEW with a valid HTTP or HTTPS URI.

val webpage = Uri.parse("https://www.justacademy.co/")
val intent = Intent(Intent.ACTION_VIEW, webpage)

if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
}

This asks Android to find a compatible activity that can display the URI. Depending on device configuration, a browser or another registered application may handle it.

11. Sharing Text Using an Intent

The ACTION_SEND action is commonly used to share text with other applications. A chooser lets the user select the destination app.

val sendIntent = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(
        Intent.EXTRA_TEXT,
        "Learn Android development with JustAcademy."
    )
}

val chooser = Intent.createChooser(
    sendIntent,
    "Share using"
)

startActivity(chooser)

The receiving app decides how to process the shared content. Avoid including passwords, private tokens, or unnecessary personal information in shared extras.

12. Creating an Intent Filter for Website Links

An activity can declare a filter for supported web links. The following example is a basic configuration for a specific HTTPS host.

<activity
    android:name=".WebLinkActivity"
    android:exported="true">

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data
            android:scheme="https"
            android:host="www.justacademy.co" />
    </intent-filter>

</activity>

The activity may be considered for matching links. For verified Android App Links, configure the appropriate host verification and the website's Digital Asset Links file as well. A manifest filter alone does not prove website ownership or guarantee that every link will open directly in the app.

13. Handling Incoming Intent Data

When an activity is opened through an implicit intent, it should inspect the action and data before deciding what to display.

class WebLinkActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_link)

        if (intent.action == Intent.ACTION_VIEW) {
            val incomingUri = intent.data

            if (incomingUri != null &&
                incomingUri.scheme == "https" &&
                incomingUri.host == "www.justacademy.co"
            ) {
                // Process the supported link.
            } else {
                // Reject or safely handle unexpected data.
            }
        }
    }
}

Never assume that incoming values are valid simply because an intent filter exists. Check the scheme, host, path, expected parameter types, and authorization requirements before using the data.

14. Intent Filters and AndroidManifest.xml

The manifest file declares application components and their externally visible capabilities. Intent filters for activities are declared in the manifest, while broadcast receivers can also register certain filters dynamically in code.

Important Manifest Attributes

Attribute or Element Purpose
android:name Identifies the component class or action/category value, depending on the element.
android:exported Controls whether other applications can access the component through normal component launching.
<intent-filter> Declares which implicit intents the component can handle.
<action> Describes the requested operation accepted by the filter.
<category> Adds a category requirement to the filter.
<data> Describes supported URI patterns and MIME types.

For apps targeting Android 12 or higher, components with intent filters must explicitly declare android:exported. Set it to true only when external applications or the system need to launch the component. Use false for internal-only components where appropriate.

15. Common Intent Actions and Their Uses

Intent Action Example Use
ACTION_VIEW Open a web page, map location, or supported content.
ACTION_SEND Share text or supported content with another app.
ACTION_DIAL Open the phone dialer with a phone number.
ACTION_SENDTO Direct a send request to a suitable recipient application.
ACTION_MAIN Represent a main application entry point.

Example: Opening the Phone Dialer

val phoneNumber = "tel:9876543210"
val intent = Intent(
    Intent.ACTION_DIAL,
    Uri.parse(phoneNumber)
)
startActivity(intent)

ACTION_DIAL opens the dialer with the number prepared. It does not automatically place the call.

16. Intent Resolution and Matching Rules

For an implicit intent, Android compares the intent against intent filters using three principal aspects.

  1. Action matching: The requested action must be compatible with an action declared by the filter.
  2. Data matching: The URI and MIME type must satisfy the filter's data requirements.
  3. Category matching: Every category present on the intent must be accepted by the filter. Ordinary implicit activity launches also require the filter to include the default category.

If the intent fails a required matching test, that filter does not match. Another eligible component or filter may still handle the request.

17. Common Errors and Troubleshooting

Error 1: ActivityNotFoundException

Cause: No suitable activity can handle an implicit intent, or the requested destination is unavailable.

Solution: Verify the intent action, URI, MIME type, installed apps, and manifest configuration. For optional external actions, handle the possibility that no suitable activity exists.

Error 2: Activity Not Declared in the Manifest

Cause: A destination activity is missing from the manifest or has an incorrect class name.

Solution: Declare the activity inside the application element and check the package and class names.

Error 3: Missing android:exported Attribute

Cause: An app targeting Android 12 or higher has a component with an intent filter but does not explicitly set its exported status.

Solution: Set android:exported="true" or "false" according to the required access.

Error 4: Intent Filter Does Not Match

Cause: The action, data URI, MIME type, or category differs from the filter declaration.

Solution: Compare the incoming intent with each filter attribute and confirm that the default category is present when required.

Error 5: Missing or Incorrect Extra

Cause: The destination activity reads an incorrect key or assumes that an extra is always present.

Solution: Use consistent key constants, provide appropriate defaults, and validate values before using them.

Error 6: Unexpected External Activity Launch

Cause: A component is exported when it does not need to be accessible to other applications.

Solution: Review component exposure, use explicit intents for internal services, validate incoming data, and avoid treating intent filters as security boundaries.

18. Best Practices for Working with Intents

  • Use explicit intents for internal activity navigation and service starts.
  • Use implicit intents when requesting an action that another compatible app may perform.
  • Validate all externally supplied intent data and extras.
  • Set android:exported deliberately for components with intent filters.
  • Use Intent.createChooser() when users should choose a sharing destination.
  • Keep extra keys consistent and use package-prefixed names for custom public keys.
  • Avoid placing sensitive information in intents that can reach other applications.
  • Handle the possibility that an implicit intent has no matching activity.
  • Keep filters focused on the specific actions and data your component supports.
  • Use verified Android App Links when a website should open reliably in your app.

19. Practical Exercises

  1. Create two activities and navigate from the first to the second using an explicit intent.
  2. Pass a student's name and course name from one activity to another using extras.
  3. Open the JustAcademy website using an implicit VIEW intent.
  4. Create a share button that shares a short message using an Android chooser.
  5. Declare an intent filter that accepts plain-text sharing and inspect the incoming action and extras.
  6. Create a basic website-link activity and validate the incoming HTTPS host before processing it.
  7. Test how your application behaves when no compatible activity is available.

20. Interview Questions and Answers

Q1. What is an intent in Android?

An intent is a messaging object used to request an action from an application component and optionally carry data to that component.

Q2. What are the two main types of intents?

Explicit intents specify the destination component, whereas implicit intents describe an action and allow Android to find a compatible component.

Q3. What is an intent filter?

An intent filter declares the actions, categories, and data patterns that a component is prepared to handle through implicit intent resolution.

Q4. What is the purpose of putExtra()?

putExtra() adds a key-value pair to an intent so the receiving component can retrieve additional information.

Q5. What is the role of AndroidManifest.xml?

The manifest declares application components, permissions, component exposure, and intent filters used for component discovery.

Q6. Why is android:exported important?

It specifies whether other applications can access a component through normal component launching. Components with intent filters in apps targeting Android 12 or higher must explicitly declare this attribute.

Q7. Can an explicit intent work without an intent filter?

Yes. An explicit intent names its destination component, so an intent filter is not required to select that destination. The component must still be declared and accessible under Android's rules.

Q8. What is ACTION_VIEW used for?

It requests that a suitable component display or open the supplied content, such as a web page or map location.

Q9. Why should an application use Intent.createChooser()?

It presents a chooser interface so the user can select a compatible application for an operation such as sharing text.

Q10. Are intent filters a security mechanism?

No. Intent filters help Android resolve implicit intents but do not prevent an application from explicitly targeting an exported component. Component exposure and input validation must be handled separately.

21. Quick Revision Checklist

  • Understand explicit and implicit intents.
  • Know the purpose of actions, data, categories, extras, and flags.
  • Understand how to declare intent filters in the manifest.
  • Practice activity navigation and data transfer with Kotlin.
  • Know how Android matches actions, data, and categories.
  • Configure component exposure using android:exported.
  • Validate incoming links and extras.
  • Handle missing destination apps and other launch errors.

22. Conclusion

Intents and intent filters are fundamental Android concepts that support activity navigation, data transfer, content sharing, and communication between applications. Explicit intents are useful when the destination is known, while implicit intents allow Android to find a suitable component for a requested action. Intent filters describe supported implicit operations, and correct manifest configuration, input validation, and component security help make applications reliable.

To continue learning Android development, explore the JustAcademy Android App Development course, visit the course demo registration page, or browse the JustAcademy website.

23. Reference

For additional technical details, consult the official Android Developers guide to intents and intent filters.

Previous Next
whatsapp